package com.lllteam.exam.account.library

import android.content.ContentValues
import android.content.Context
import android.net.Uri
import android.util.Log
import com.lllteam.exam.account.library.provider.AccountProvider

object DataStore {
    fun saveAccount(context: Context, account :Account): Uri? {
        val values = ContentValues()

        values.put(
            AccountProvider.NAME, account.name
        )

        values.put(
            AccountProvider.EN_NAME, account.enName
        )

        values.put(
            AccountProvider.GRADE, account.grade
        )

        values.put(
            AccountProvider.MOBILE, account.mobile
        )

        values.put(
            AccountProvider.SEQ_ID, account.seqId
        )

        values.put(
            AccountProvider.SCHOOL, account.school
        )

        values.put(
            AccountProvider.ADDRESS, account.address
        )

        context.contentResolver.delete(AccountProvider.COURSE_URI, null, null)
        return context.contentResolver.insert(
            AccountProvider.COURSE_URI, values
        )
    }

    fun getAccount(context: Context): Account? {
        val cursor = context.contentResolver.query(AccountProvider.COURSE_URI, null, null, null, null)
        val list = mutableListOf<Account>()
        cursor?.let {
            while (it.moveToNext()) {
                val name = it.getString(it.getColumnIndex(AccountProvider.NAME))
                val enName = it.getString(it.getColumnIndex(AccountProvider.EN_NAME))
                val grade = it.getString(it.getColumnIndex(AccountProvider.GRADE))
                val mobile = it.getString(it.getColumnIndex(AccountProvider.MOBILE))
                val seqId = it.getString(it.getColumnIndex(AccountProvider.SEQ_ID))
                val school = it.getString(it.getColumnIndex(AccountProvider.SCHOOL))
                val address = it.getString(it.getColumnIndex(AccountProvider.ADDRESS))
                list.add(Account(name, enName, grade, mobile, seqId, school, address))
            }
            it.close()
        }
        Log.d(LoginActivity.TAG, "accounts $list")

        return if (list.isNotEmpty()) {
            list.last()
        } else {
            null
        }
    }
}